package org.kjtc.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.kjtc.entity.Template;
import org.kjtc.entity.WechatMessage;
import org.kjtc.entity.WechatUser;
import org.kjtc.entity.WorkContent;
import org.kjtc.service.WeChartService;
import org.kjtc.weChatUtil.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 发送消息 TODO
 */

@Controller
public class MessageController {

    private static Logger logger = Logger.getLogger(MessageController.class);

    @Autowired
    private WeChartService weChartService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @RequestMapping("/sendWeChatMessage")
    @ResponseBody
    public Object sendWeChatMessage(HttpServletRequest request, @RequestBody String requestBody, WeChartService requestWeChartService, RedisTemplate<String, Object> requestRedisTemplate) {
        if (weChartService == null) {
            weChartService = requestWeChartService;
        }
        if (redisTemplate == null) {
            redisTemplate = requestRedisTemplate;
        }
        JSONObject json = JSONObject.fromObject(requestBody);
        logger.info("微信公众号服务接收到信息：" + json.toString());
        Map<String, Object> map = new HashMap<String, Object>();
        if (json != null && !json.isNullObject() && !json.isEmpty()) {
            WechatMessage wechatMessage = new WechatMessage();
            wechatMessage.setSendDTTM(new Date());
            String notExistUserID = json.has("userID") ? json.getString("userID") : "";
            notExistUserID += json.has("openID") ? json.getString("openID") : "";
            String sendResult = null;
            String sendUser = "";
//            String url = "http://www.kejiatc.cn/login.jsp";
            wechatMessage.setType(json.has("type") ? json.getString("type") : "");
            wechatMessage.setSendFrom(json.has("sendFrom") ? json.getString("sendFrom") : "未知");
            wechatMessage.setTemplateID(json.has("templateID") ? json.getString("templateID") : "");
            wechatMessage.setUrl(json.has("url") && !StringUtils.isEmpty(json.getString("url"))? json.getString("url") : null);
            wechatMessage.setAppid(json.has("appid") ? json.getString("appid") : "");
            wechatMessage.setPagepath(json.has("pagepath") ? json.getString("pagepath") : "");
            wechatMessage.setCreateUser("weChatMessage");
            wechatMessage.setUpdateUser("weChatMessage");
            weChartService.saveWechatMessage(wechatMessage);
            if (!json.has("templateID")) {
                map.put("result", "TemplateIDEmpty");
                sendResult = "发送失败：模板(templateID)不存在";
                logger.error("微信消息发送失败，发送消息模板(templateID)不存在：" + json.toString());
            } else if (!json.has("data")) {
                map.put("result", "DataEmpty");
                sendResult = "发送失败：信息内容(data)不存在";
                logger.error("微信消息发送失败，发送信息内容(data)不存在：" + json.toString());
            } else if (StringUtils.isEmpty(notExistUserID)) {
                map.put("result", "UserEmpty");
                sendResult = "发送失败：发送用户不存在";
                logger.error("微信消息发送失败，发送用户不存在：" + json.toString());
            } else {
                WechatUser wechatUser = new WechatUser();
                if (json.has("userID") && !StringUtils.isEmpty(json.getString("userID"))) {
                    wechatUser.setUserID(json.getString("userID"));
                }
                if (json.has("openID") && !StringUtils.isEmpty(json.getString("openID"))) {
                    wechatUser.setWeChatID(json.getString("openID"));
                }
                List<WechatUser> wechatUserList = weChartService.getSendUser(wechatUser);
                wechatUser = null;
                String sendSuccessResult = null;
                String sendFailResult = null;
                if (wechatUserList.size() > 0) {
                    String token = CommonUtil.getToken(CommonUtil.appid, CommonUtil.appsecret, redisTemplate);
                    if (StringUtils.isEmpty(token)) {
                        map.put("result", "TokenError");
                        sendResult = "发送失败：获取微信(token)失败";
                    } else {
                        Template template = new Template();
                        template.setTemplateId(json.getString("templateID"));
                        if (json.has("url") && !StringUtils.isEmpty(json.getString("url"))) {
                            template.setUrl(CommonUtil.baseUrl_kejiatc + "getAuthorizeBaseCode" + "?id=" + wechatMessage.getID() + "&url=" + json.getString("url"));
                        }
                        template.setTopColor("#FF0000");
                        template.setAppid(json.has("appid") && !"-".equals(json.getString("appid")) && !"null".equals(json.getString("appid").toLowerCase()) ? json.getString("appid") : "");
                        template.setAppid(json.has("pagepath") && !"-".equals(json.getString("pagepath")) && !"null".equals(json.getString("pagepath").toLowerCase()) ? json.getString("pagepath") : "");
                        template.setData(json.getString("data"));
                        String successUser = null;
                        String failUser = null;
                        Map<String, Object> resultMap = new HashMap<String, Object>();
                        for (WechatUser wechatUserTemp : wechatUserList) {
                            if (wechatUserTemp.isEnabled()) {
                                template.setToUser(wechatUserTemp.getWeChatID());
                                int errorCode = CommonUtil.sendMessage(token, template);
                                if (errorCode == 0) {
                                    if (successUser == null ) {
                                        successUser = wechatUserTemp.getUserID();
                                    } else {
                                        successUser += "," + wechatUserTemp.getUserID();
                                    }
                                    if (sendSuccessResult == null) {
                                        sendSuccessResult = "发送成功：" + wechatUserTemp.getWeChatNickName() + "-" + wechatUserTemp.getUserName();
                                    } else {
                                        sendSuccessResult += "," + wechatUserTemp.getWeChatNickName() + "-" + wechatUserTemp.getUserName();
                                    }
                                    logger.info("微信消息发送【" + wechatUserTemp.getWeChatNickName() + "-" + wechatUserTemp.getUserName() + "】成功");
                                } else {
                                    if (failUser == null ) {
                                        failUser = wechatUserTemp.getUserID();
                                    } else {
                                        failUser += "," + wechatUserTemp.getUserID();
                                    }
                                    if (sendFailResult == null) {
                                        sendFailResult = "发送失败：" + wechatUserTemp.getWeChatNickName() + "-" + wechatUserTemp.getUserName() + "(" + CommonUtil.getErrorReason(errorCode) + ")";
                                    } else {
                                        sendFailResult += "," + wechatUserTemp.getWeChatNickName() + "-" + wechatUserTemp.getUserName() + "(" + CommonUtil.getErrorReason(errorCode) + ")";
                                    }
//                                    redisTemplate.delete(CommonUtil.Redis_WeChat_AccessToken);
                                    logger.error("微信消息发送【" + wechatUserTemp.getWeChatNickName() + "-" + wechatUserTemp.getUserName() + "】失败：" + CommonUtil.getErrorReason(errorCode));
                                }
                            } else {
                                if (failUser == null ) {
                                    failUser = wechatUserTemp.getUserID();
                                } else {
                                    failUser += "," + wechatUserTemp.getUserID();
                                }
                                if (sendFailResult == null) {
                                    sendFailResult = "发送失败：" + wechatUserTemp.getWeChatNickName() + "-" + wechatUserTemp.getUserName() + "(用户不可用或未关注)";
                                } else {
                                    sendFailResult += "," + wechatUserTemp.getWeChatNickName() + "-" + wechatUserTemp.getUserName() + "(用户不可用或未关注)";
                                }
                                logger.error("微信消息发送【" + wechatUserTemp.getWeChatNickName() + "-" + wechatUserTemp.getUserName() + "】失败：用户不可用或未关注");
                            }
                            if (sendUser == null || "".equals(sendUser)) {
                                sendUser = wechatUserTemp.getWeChatNickName() + "-" + wechatUserTemp.getUserName();
                            } else {
                                sendUser += "," + wechatUserTemp.getWeChatNickName() + "-" + wechatUserTemp.getUserName();
                            }
                            if (notExistUserID != null) {
                                notExistUserID = notExistUserID.replaceAll("'", "");
                                if (!StringUtils.isEmpty(wechatUserTemp.getUserID())) {
                                    notExistUserID = notExistUserID.replace(wechatUserTemp.getUserID() + ",", "").replace(wechatUserTemp.getUserID(), "");
                                }
                                if (!StringUtils.isEmpty(wechatUserTemp.getWeChatID())) {
                                    notExistUserID.replace(wechatUserTemp.getWeChatID() + ",", "").replace(wechatUserTemp.getWeChatID(), "");
                                }
                            }
                        }
                        if (successUser != null) {
                            resultMap.put("successUser", successUser);
                        }
                        if (failUser != null) {
                            resultMap.put("failUser", failUser);
                        }
                        map.put("result", resultMap);
                        sendResult = "";
                        if (sendSuccessResult != null) {
                            sendResult += sendSuccessResult + "；";
                        }
                        if (sendFailResult != null) {
                            sendResult += sendFailResult + "；";
                        }
                        if (notExistUserID != null && !"".equals(notExistUserID)) {
                            sendResult += "未关注：" + notExistUserID + "；";
                        }
                        successUser = null;
                        failUser = null;
                        template = null;
                    }
                } else {
                    map.put("result", "NotExistUser");
                    sendResult = "发送失败：所有用户未关注" + notExistUserID;
                    logger.error("微信消息发送失败，所有发送用户都不存在：" + json.toString());
                }
            }
            if (notExistUserID != null && !"".equals(notExistUserID)) {
                sendUser = notExistUserID + "," + sendUser;
            }
            wechatMessage.setSendUser(sendUser);
            String data = json.has("data") ? json.getString("data") : "";
            wechatMessage.setData(data);
            String message = "";
            int k = 1;
            if (data != null && !"".equals(data)) {
                JSONObject jsonData = JSONObject.fromObject(data);
                JSONObject jsonKeyword = null;
                while (jsonData.has("keyword" + k)) {
                    jsonKeyword = JSONObject.fromObject(jsonData.get("keyword" + k));
                    if (jsonKeyword.has("value")) {
                        message += jsonKeyword.get("value") + "  ";
                    }
                    k++;
                    jsonKeyword = null;
                }
                jsonData = null;
            }
            wechatMessage.setMessage(message);
            wechatMessage.setUrl(json.has("url") && !StringUtils.isEmpty(json.getString("url")) ? (CommonUtil.baseUrl_kejiatc + "getAuthorizeBaseCode" + "?id=" + wechatMessage.getID() + "&url=" + json.getString("url")) : null);
            wechatMessage.setSendResult(sendResult);
            wechatMessage.setUpdateUser("weChat");
            weChartService.updateWechatMessage(wechatMessage);
            logger.info("数据库更新接收到的信息");
            wechatMessage = null;
            sendUser = null;
            notExistUserID = null;
            data = null;
            message = null;

        } else {
            map.put("result", "Empty");
            logger.error("微信消息发送失败，请求数据为空。");
        }
        json = null;
        return map;
    }

    @RequestMapping(value = "/searchWechatMessage")
    @ResponseBody
    public Map<String, Object> searchWechatMessage(WechatMessage wechatMessage,
            @RequestParam(value="pageNum", defaultValue="1") Integer pageNum, @RequestParam(value="pageSize", defaultValue="10") Integer pageSize) {

        Page page = PageHelper.startPage(pageNum, pageSize);
        Map<String, Object> map = new HashMap<String, Object>();
        List<WechatMessage> messagelist = null;
        try {
            messagelist = weChartService.searchWechatMessagePage(wechatMessage);
        } catch (Exception e) {
            e.printStackTrace();
        }
        map.put("messagelist", messagelist);
        map.put("total", page.getTotal());
        return map;
    }

    @RequestMapping(value = "/getAlarmWarning")
    public String getAlarmWarning(String id, String userID, Model model) {
        WechatMessage wechatMessage = new WechatMessage();
        List<WechatMessage> messagelist = null;
        List<WorkContent> workList = null;
        List<WechatUser> userList = null;
        try {
            wechatMessage.setID(Integer.parseInt(id));
            messagelist = weChartService.searchWechatMessage(wechatMessage);
            JSONObject jsStr = JSONObject.fromObject(messagelist.get(0).getData());
            WechatUser wechatUser = new WechatUser();
            wechatUser.setUserID("'" + userID + "'");
            userList = weChartService.searchWechatUser(wechatUser);
        } catch (Exception e) {
            e.printStackTrace();
        }
        model.addAttribute("messagelist", messagelist);
        model.addAttribute("userList", userList);
        return "weChat/wechatAlarmWarning";
    }
}